#include "SocketComm.h"
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

//Default constructor
SocketComm::SocketComm()
{
}

//Constructor
SocketComm::SocketComm(int nodeOne, int nodeTwo)
{
    //Ensure that nodes[0] is always the lesser of the two values
    if(nodeOne > nodeTwo)
    {
        int temp = nodeOne;
        nodeOne = nodeTwo;
        nodeTwo = temp;
    }
    
    //Store the node addresses that this object connects
    nodes[0] = nodeOne;
    nodes[1] = nodeTwo;

    //creates the socketpair connection to set up the pipes
    if(socketpair(AF_UNIX, SOCK_STREAM, 0, socket) != 0)
    {
        char message[50];
        sprintf(message, "Error in creating socket between %d and %d", nodes[0], nodes[1]);
        perror(message);
        exit(1);
    }

    //Set the pipes to nonblocking reads
    fcntl(socket[0], F_SETFL, fcntl(socket[0], F_GETFL, 0) | O_NONBLOCK);
    fcntl(socket[1], F_SETFL, fcntl(socket[1], F_GETFL, 0) | O_NONBLOCK);
}

//Return an int array of size 2 that holds the addresses of the two
//objects that this object connects
int* SocketComm::getPair()
{
    return nodes;
}

//Return an int array of size 2 that holds the pipes that allow communication
//between the two processes that this object connects.
int* SocketComm::getSocket()
{
    return socket;
}

//Close both sockets of this object
void SocketComm::closeSockets()
{
    closeSocket(0);
    closeSocket(1);
}

//Close a single end of the socket
void SocketComm::closeSocket(int end)
{
    close(socket[end]);
}
